package com.lambkit.component.nacos;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.lambkit.Lambkit;
import com.lambkit.common.bean.LambkitBeanManager;
import com.lambkit.common.bean.ActionBean;
import com.lambkit.common.bean.ActionMapping;
import com.lambkit.plugin.api.route.ApiAction;
import com.lambkit.plugin.api.route.ApiRoute;
import com.lambkit.plugin.api.route.ApiStore;
import com.lambkit.plugin.gateway.RouteServiceInstance;

public class Nacos {

	private static NacosClient client;

	public static NacosClient use() {
		if (client == null) {
			client = new NacosClient(Lambkit.config(NacosConfig.class));
		}
		client.setConfig(Lambkit.config(NacosConfig.class));
		return client;
	}

	public static String getServiceName(RouteServiceInstance rsi) {
		StringBuffer strb = new StringBuffer();
		strb.append("http-");
		strb.append(rsi.getType());
		strb.append("-");
		strb.append(rsi.getName().replaceAll("/", "."));
		String serviceName = strb.toString();
		return serviceName;
	}

	public static String getServiceName(String protocol, String type, String name) {
		StringBuffer strb = new StringBuffer();
		strb.append(protocol);
		strb.append("-");
		strb.append(type);
		strb.append("-");
		strb.append(name.replaceAll("/", "."));
		String serviceName = strb.toString();
		return serviceName;
	}

	public static void start() {
		// 加入Api到Consul，用于HttpRpc
		ApiStore apiStore = ApiRoute.me().getApiStore();
		ConcurrentHashMap<String, ApiAction> apiMap = apiStore.getApiMap();
		for (String key : apiMap.keySet()) {
			StringBuffer strb = new StringBuffer();
			strb.append("http-").append("apiroute-").append(key);
			String serviceName = strb.toString();
			try {
				use().registerInstance(serviceName);
			} catch (NacosException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 加入Controller到Consul，用户Gateway
		ActionMapping actionMapping = LambkitBeanManager.me().getInfo().getActionMapping();
		Map<String, ActionBean> mapping = actionMapping.getMapping();
		for (String key : mapping.keySet()) {
			StringBuffer strb = new StringBuffer();
			strb.append("http-").append("action-").append(key.replaceAll("/", "."));
			String serviceName = strb.toString();
			try {
				use().registerInstance(serviceName);
			} catch (NacosException e) {
				e.printStackTrace();
			}
		}

		StringBuffer strb = new StringBuffer();
		strb.append("http-").append("apiroute-").append("sdss.version");
		try {
			List<Instance> insts = use().getAllInstances(strb.toString());
			for (Instance instance : insts) {
				System.out.println(instance);
			}
		} catch (NacosException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void stop() {

	}
}
